package org.hackystat.ambientdevice.xml;

import java.io.File;
import java.io.FileOutputStream;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.hackystat.ambientdevice.server.jaxb.Configuration;

/**
 * Writes the configuration file to an xml file on the user's computer.
 * 
 * @author Sonwright M. Gomez
 *
 */
public class ConfigurationSaver {

  /** Holds the class-wide JAXBContext, which is thread-safe. */
  private JAXBContext configurationJaxbContext;
  
  /**
   * Initializes the instance.
   * 
   * @throws Exception if problem exists.
   */
  public ConfigurationSaver () throws Exception {
    String jaxbContentString = "org.hackystat.ambientdevice.server.jaxb";
    this.configurationJaxbContext = JAXBContext.newInstance(jaxbContentString);
  }
  
  /**
   * Attempts to save the Configuration File to the user directory.
   * 
   * @param configuration the configuration to be saved.
   * @throws JAXBException if problems exists.
   * @return some kind of boolean
   */
  public boolean saveConfigurationXml (Configuration configuration) throws JAXBException {
    String username = configuration.getUser().getEmail().replace('@', '_').replace('.', '_');
    
    //Attempts to create the configuration file.
    try {
      String currentWorkingDirectory = System.getProperty("user.dir");
      String configurationFilePath = currentWorkingDirectory + "/xml/users/" + username + ".xml";
      Marshaller marshaller = this.configurationJaxbContext.createMarshaller();
      marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
      
      //Checks to make sure that there is a file found within the configuration file path. If
      //no file is found, then it creates a newfile and writes it there.
      File file = new File(configurationFilePath);
      if (!file.exists()) {
        file.createNewFile();
      }
      marshaller.marshal(configuration, new FileOutputStream(configurationFilePath));
      return true;
    }
    catch (Exception e) {
      e.printStackTrace();
      e.getMessage();
      return false;
    }
  }
    
  
}
